<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use backend\models\Category;
use backend\models\Goods;

class CategoryController extends BaseController{

	public $nodeName = '分类管理';
	public $init_upload_image = '/common/uploads/system/upload.jpg';

	public function init(){
        parent::init();
	}

	public function actionLists(){
		return $this->render('lists');
	}

	public function actionCreate(){
		$id = $this->request->get('id');

		if(!empty($id)){
			$category = Category::findOne($id);
			$category->setScenario('update');
		}else{
			$category = new Category;
			$category->setScenario('create');
		}

		if($this->request->isPost){
			if($category && $category->load($this->request->post())){
				if($category->save()){
					$this->session->setFlash('success', '保存成功!');
					return $this->redirect(['category/lists']);
				}else{
					$this->session->setFlash('error', '保存失败!');
				}
			}else{
				$this->session->setFlash('error', '???????!!!!!');
			}

		}
		$result = [
			'category' => $category,
			'pageTitle' => '创建分类',
		];

		return $this->render('data-form', $result);
	}

	public function actionDel(){
        $id = $this->request->get('id');

        if(!empty($id)){
            $category = Category::findOne($id);
            $category->setScenario('update');
        }else{
            $this->session->setFlash('error', '错误1!');
        }

        if(!empty(Goods::findOne(['cid' => $category->id])) || !empty(Category::findOne(['pid' => $category->id]))){
            $this->session->setFlash('error', '无法删除非空类!');
            return $this->redirect(Yii::$app->request->referrer);
        }

        if($category->delete()){
            $this->session->setFlash('success', '删除成功!');
            return $this->redirect(Yii::$app->request->referrer);
        }

        $this->session->setFlash('error', '错误2!');
        return $this->redirect(Yii::$app->request->referrer);
	}

    public function actionValidateForm ($id = null) {

        if($id === null){
            $model = new Category();
            $model->setScenario('create');
        }else{
            $model = Category::findOne($id);
            $model->setScenario('update');
        }
        $model->load($this->request->post());

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return \yii\widgets\ActiveForm::validate($model);
    }

    /**
     * 数据迁移
     * 迁移分类下面的子分类及数据
     */
    public function actionMoveData(){
        $id = $this->request->get('id');

        if(!empty($id)){
            $category = Category::findOne($id);
        }else{
            $this->session->setFlash('error', '错误1!');
        }

        
    }
}